package com.miracle.controller;

import com.miracle.config.RestTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author jie.xi
 * @date 2022年04月27日 15:31
 */

@RestController
@Slf4j
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/user/getProductInfo")
    public String getProductInfo(@RequestParam("id") String productId){
        /*//调用商品服务
        //1. restTemplate直接调用(缺点：无法实现负载均衡以及代码写死了)
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject("http://localhost:9098/product/find/?id=" + productId, String.class);
        log.info("返回的信息：[{}]"+forObject);*/



        /*//第二种调用方式：restTemplate + ribbon 负载均衡客户端 DiscoveryClient  LoadBalanceClient   注解形式
        List<ServiceInstance> products = discoveryClient.getInstances("products");
        for(ServiceInstance product : products){
            log.info("服务地址：[{}]",product.getUri());
        }
        ServiceInstance productsServiceInstances = loadBalancerClient.choose("products");
        log.info("当前处理服务负载均衡的客户端主机为：[{}]" , productsServiceInstances);
        String forObject1 = restTemplate.getForObject(productsServiceInstances.getUri() + "/product/find?id=" + productId, String.class);
        log.info("返回的信息：[{}]",forObject1);*/


        //第三种调用方式，config一个restTemplate，使用loadBalanceClient注解
        //服务名+地址
        String forObject2 = restTemplate.getForObject("http://products/product/find?id=" + productId, String.class);
        log.info("返回的信息：[{}]",forObject2);
        return forObject2;
    }
}
